﻿using UnityEngine;
using UnityEngine.UI;

namespace UFrame
{
    /// <summary>
    /// 计算文本长度,并且设置到Text RectTransform 组件中
    /// </summary>
    public class CalTextSize : MonoBehaviour
    {
        public RectTransform sizeRect;
        public Text text;


        public void Awake()
        {
            CalSize();
        }

        public void CalSize()
        {
            if (sizeRect == null)
                sizeRect = GetComponent<RectTransform>();
            if (text == null)
                text = GetComponent<Text>();

            CalSize(sizeRect, text);
        }

        public static float CalSize(RectTransform rect, Text text)
        {
            string message = text.text;
            int totalLength = 0;
            Font myFont = text.font;
            myFont.RequestCharactersInTexture(message, text.fontSize, text.fontStyle);
            CharacterInfo characterInfo = new CharacterInfo();
            char[] arr = message.ToCharArray();
            foreach (char c in arr)
            {
                myFont.GetCharacterInfo(c, out characterInfo, text.fontSize);
                totalLength += characterInfo.advance;
            }

            rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, totalLength);
            Debug.Log("计算文字的长度 " + totalLength);
            return totalLength;
        }
    }
}